/**
 * 注册websocket
 * @mask 支持promise返回,也支持回调返回
 * @param path websocket地址
 * @param onMsg  接收推送的回调函数
 * @param onOpen 连接消息
 * @param onErr 错误消息
 * @returns {Promise}
 */
export function websocket(opt = {
  path: '', onMsg: () => {
  }, onOpen: () => {
  }, onErr: () => {
  }
}) {
  return new Promise((resolve, reject) => {
    console.log(opt.path);
    try {
      let ws = new WebSocket(opt.path)
      let heartTimer
      // 绑定消息
      ws.onmessage = (msg) => {
        if (msg.data !== 'heart') { // 非心跳包返回
          if (opt.onMsg) opt.onMsg(msg, ws)
          resolve(msg, ws);
        }
      }
 
      ws.onopen = (event) => { // 绑定连接消息
        if (opt.onOpen) opt.onOpen(event, ws);
        // heartTimer = setInterval(() => { // 连接成功后发2秒心跳包
        //   ws.send('heart')
        // }, 2000)
      }
 
      ws.onerror = (err) => { // 绑定错误消息
        console.log(err);
        if (opt.onErr) opt.onErr(err, ws)
        reject(err, ws);
        clearTimeout(heartTimer)
      }
      ws.onclose = () => {
        ws.close();
        clearTimeout(heartTimer)
      }
    } catch (e) {
      console.log(e);
      reject();
    }
  })
}
 
export default websocket;